package cn.flying.base.web.auth.session;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.session.InvalidSessionStrategy;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;

import cn.flying.base.common.enums.RtCodeEnum;
import cn.flying.base.common.vo.Rt;
import cn.flying.base.core.common.utils.Ft;
import cn.flying.base.web.auth.configuration.LoginUser;
import cn.flying.base.web.auth.domain.SysLoginLog;
import cn.flying.base.web.auth.service.SysUserService;

/**
 * @description: 正常session过期策略，或者服务重启导致session不可用
 * @author: lvyong
 * @date: 2023年06月02日 22:03
 * @version: 1.0
 */
@Component
public class SessionInvalidStrategy implements InvalidSessionStrategy {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private SysUserService sysUserService;

    @Override
    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        logger.info("当前登录已失效，请重新登录！");
        try {
            SecurityContext context = SecurityContextHolder.getContext();
            Authentication authentication = context.getAuthentication();
            LoginUser loginUser = sysUserService.findUserByUsername(request.getParameter("username"));
            if (Objects.nonNull(loginUser)) {
                //保存登录日志
                SysLoginLog loginLog = new SysLoginLog();
                loginLog.setUserId(loginUser.getUserId());
                loginLog.setUserName(loginUser.getUsername());
                loginLog.setName(loginUser.getName());
                //I 登入成功 O 登出成功  F 登入失败  T 会话失效
                loginLog.setHappenType("T");
                loginLog.setHappenTime(new Date());
                loginLog.setHappenIp(Ft.Network.getIpAddress(request));
                loginLog.setRemark("会话过期失效");
                loginLog.setTenantId(loginUser.getTenantId());
                loginLog.setCreatedBy(loginUser.getUsername());
                loginLog.setCreatedTime(new Date());
                loginLog.setUpdatedBy(loginUser.getUsername());
                loginLog.setUpdatedTime(new Date());
                loginLog.setRevision(0L);
                sysUserService.insertLoginLog(loginLog);
            }
        } catch (Exception e) {
            logger.warn("系统登录日志保存失败，异常原因【{}】", e.getMessage());
        }

        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(Rt.error(RtCodeEnum.R10017)));
        out.flush();
        out.close();
    }
}
